package com.november.lottery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.november.lottery.base.BaseException;
import com.november.lottery.base.MyServiceImpl;
import com.november.lottery.constant.HttpCustomStatusEnum;
import com.november.lottery.domain.Member;
import com.november.lottery.mapper.MemberMapper;
import com.november.lottery.service.MemberService;
import com.november.lottery.wx.WxMpConfiguration;
import lombok.extern.java.Log;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;


/**
 * 平台活动上架接口实现层
 * @author Administrator
 */
@Log
@Service
public class MemberServiceImpl extends MyServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private WxMpConfiguration wxMpConfiguration;

    @Override
    public Member checkExist(String openId, String classify) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id", openId);
        queryWrapper.eq("classify", classify);
        return getOne(queryWrapper);
    }

    @Override
    public List<Member> getUnusedList(String classify) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("result");
        queryWrapper.eq("classify", classify);
        List<Member> list = list(queryWrapper);
        // 去除已对过奖的
        List<Member> canList = list.stream()
                .filter(item -> item.getResult() == null || Objects.equals(item.getResult(), ""))
                .collect(Collectors.toList());
        return canList;
    }

    @Override
    public List<Member> listByClassify(String classify) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classify", classify);
        return list(queryWrapper);
    }

    @Override
    public Member join(String code, String classify) throws BaseException {
        // 获取
        WxMpService wxMpService = wxMpConfiguration.service();
        try {
            // 微信code获取微信openId
            WxMpOAuth2AccessToken auth2AccessToken = wxMpService.oauth2getAccessToken(code);
            WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(auth2AccessToken, "zh_CN");
            String openId = wxMpUser.getOpenId();
            // 从微信获取信息
            Member member = new Member();
            member.setNickname(wxMpUser.getNickname());
            member.setOpenId(openId);
            member.setAvatar(wxMpUser.getHeadImgUrl());
            member.setCountry(wxMpUser.getCountry());
            member.setProvince(wxMpUser.getProvince());
            member.setCity(wxMpUser.getCity());
            member.setClassify(classify);
            // 检测openid是否重复
            Member check = checkExist(openId, classify);
            if (check == null) {
                // 生成4位兑奖码
                // 获取最大序号
                Integer sort = getNextSort(classify);
                String number = genCode(classify, sort);
                member.setSort(sort);
                member.setNumber(number);
                check = saveOrUpdateAndReturn(member);

            }
            // 保存进数据库
            return check;
        } catch (WxErrorException e) {
            throw new BaseException(HttpCustomStatusEnum.DATA_NOT_FOUND, "未能获取到微信授权");
        }
    }
    private Member getByNumber(String number, String classify) {
        QueryWrapper<Member> query = new QueryWrapper<>();
        query.eq("number", number);
        query.eq("classify", classify);
        return getOne(query);
    }

    @Override
    public String genCode(String classify, Integer sort) throws BaseException {
        String number = random4();
        // 检查是否重复，重复了就+1 直到没有
        for(int i = 0; i< 100;i++) {
            Member check = getByNumber(number, classify);
            if(check==null) {
                return number;
            }
            log.warning(classify+":出现碰撞:"+i);
        }
        throw BaseException.throwDataError("报名失败，名额已满");
    }

    private String random4() {
        Random random = new Random(System.currentTimeMillis());
        int s0 = random.nextInt(10);
        int s1 = random.nextInt(10);
        int s2 = random.nextInt(10);
        int s3 = random.nextInt(10);
        return ""+ s0 + s1 + s2 + s3;
    }

    @Override
    public Integer getNextSort(String classify) {
        QueryWrapper<Member> query = new QueryWrapper<>();
        query.eq("classify", classify);
        query.last("order by sort desc");
        Member one = getOne(query);
        // 序号从1234起
        Integer sort = one == null ? Integer.valueOf(123) : one.getSort();
        sort = sort>123?sort: 123;
        sort+=3;
        return sort;
    }
}
